# -*- encoding=UTF-8 -*-

from now import app, db
from flask import render_template, redirect, request, flash, get_flashed_messages
from now.models import Image, User, Comment
from flask_login import login_user, logout_user, login_required, current_user
import hashlib
import random
import json
import os
import uuid


# 首页
@app.route('/')
@app.route('/index/')
def index():
    paginate = Image.query.order_by(db.desc(Image.id)).paginate(page=1, per_page=15)
    return render_template('index.html', images=paginate.items, has_next=paginate.has_next)

# 首页更多图片
@app.route('/images/<int:page>/<int:per_page>/')
def all_images(page, per_page):
    global comment
    paginate = Image.query.order_by(db.desc(Image.id)).paginate(page=page, per_page=per_page)
    map = {'has_next': paginate.has_next}
    images = []
    for image in paginate.items:
        imgvo = {
                 'user_id': image.user_id,
                 'user_head_url': image.user.head_url,
                 'user_name': image.user.username,
                 'img_id': image.id,
                 'img_url': image.url,
                 'img_date': str(image.created_date),
                 'comment_count': len(image.comments),
                 'comments': ''
                 }
        comment = ''
        try:
            comment = [{'username': image.comments[0].user.username, 'user_id': image.comments[0].user_id, 'comments': image.comments[0].comments},
                       {'username': image.comments[1].user.username, 'user_id': image.comments[1].user_id, 'comments': image.comments[1].comments},
                       {'username': image.comments[2].user.username, 'user_id': image.comments[2].user_id, 'comments': image.comments[2].comments}]
        except:
            pass
        imgvo["comments"] = comment
        images.append(imgvo)
    map['images'] = images
    return json.dumps(map)

# 个人信息
@app.route('/profile/<int:user_id>/')
@login_required
def profile(user_id):
    user = User.query.get(user_id)
    if user == None:
        return redirect('/')
    paginate = Image.query.order_by(db.desc(Image.id)).filter_by(user_id=user_id).paginate(page=1, per_page=3)
    imgs = Image.query.filter_by(user_id=user_id).count()
    return render_template('profile.html', user=user, images=paginate.items, has_next=paginate.has_next, imgs=imgs)

# 图片详情
@app.route('/image/<int:image_id>/')
@login_required
def image(image_id):
    image = Image.query.get(image_id)
    return render_template('pageDetail.html', image=image )


@app.route('/profile/images/<int:user_id>/<int:page>/<int:per_page>/')
@login_required
def user_images(user_id, page, per_page):
    paginate = Image.query.filter_by(user_id=user_id).order_by(db.desc(Image.id)).paginate(page=page, per_page=per_page)
    map = {'has_next': paginate.has_next}
    images = []
    for image in paginate.items:
        imgvo = {'id': image.id, 'url': image.url, 'command_count': len(image.comments)}
        images.append(imgvo)
    map['images'] = images
    return json.dumps(map)

# 登录注册
@app.route('/reglogin/')
def reglogin():
    msg = ''
    for m in get_flashed_messages(with_categories=False, category_filter=['reglogin']):
        msg = msg + m

    return render_template('login.html', msg=msg, next=request.values.get('next'))

def redirect_with_msg(target, msg, category):
    if msg != None:
        flash(msg, category=category)
    return redirect(target)

# 注册
@app.route('/reg/', methods={'post', 'get'})
def reg():
    username = request.values.get('username').strip()
    password = request.values.get('password').strip()

    if username == '' or password == '':
        return redirect_with_msg('/reglogin/', u'用户名或者密码不能为空', 'reglogin')

    user = User.query.filter_by(username=username).first()
    if user != None:
        return redirect_with_msg('/reglogin/', u'用户名已经存在', 'reglogin')

    salt = '.'.join(random.sample('0123456789abcdefghijklmnopqrstuvwxy', 10))
    m = hashlib.md5()
    m.update((password+salt).encode('utf-8'))
    password = m.hexdigest()
    user = User(username, password, salt)
    db.session.add(user)
    db.session.commit()

    login_user(user)
    next_msg = request.values.get('next').strip()
    if next_msg != None and next_msg.startswith('/'):
        return redirect(next_msg)
    return redirect('/profile/'+str(user.id)+'/')

# 退出登录
@app.route('/logout/')
def logout():
    logout_user()
    return redirect('/')

# 登录验证
@app.route('/login/', methods={'post', 'get'})
def login():
    username = request.values.get('username').strip()
    password = request.values.get('password').strip()

    if username == '' or password == '':
        return redirect_with_msg('/reglogin/', u'用户名不能为空', 'reglogin')
    user = User.query.filter_by(username=username).first()
    if user == None:
        return redirect_with_msg('/reglogin/', u'用户名不存在', 'reglogin')

    m = hashlib.md5()
    m.update((password+user.salt).encode('utf-8'))
    if m.hexdigest() != user.password:
        return redirect_with_msg('/reglogin/', u'密码错误', 'reglogin')
    login_user(user)

    next_msg = request.values.get('next').strip()
    if next_msg != None and next_msg.startswith('/'):
        return redirect(next_msg)

    return redirect('/profile/'+str(user.id)+'/')

# 保存图片
def save_to_local(file, file_name):
    save_dir = os.getcwd()
    file_path = os.path.join(save_dir,  'now/static/images/img', file_name)
    file.save(file_path)
    #print(file_path)
    return '/static/images/img/' + file_name

# 上传图片
@app.route('/upload/', methods={'post'})
def upload():
    file = request.files['file']
    file_ext = ''
    if file.filename.find('.') > 0:
        file_ext = file.filename.rsplit('.', 1)[1].strip().lower()
    if file_ext in app.config['ALLOWED_EXT']:
        file_name = str(uuid.uuid1()).replace('-', '') + '.' + file_ext
        url = save_to_local(file, file_name)
        if url != None:
            db.session.add(Image(url, current_user.id))
            db.session.commit()

    return redirect('/profile/%d' % current_user.id)


@app.route('/getPosts', methods = {'get'})
@login_required
def getPosts():
    length = Image.query.filter_by(user_id=current_user.id).count()
    return str(length)








